<template>
<div class="bargain-add views-container">
    <div class="wlm-form">
        <div class="wlm-form-header">活动设置</div>
        <div class="wlm-form-content">
            <el-form ref="active" :disabled="$hasFormEnd" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="144px" class="retail-form" label-position="right">
                <el-form-item label="活动名称" prop="name">
                    <el-input :maxlength="50" v-model.trim="formFormatData.formData.name">
                    </el-input>
                </el-form-item>
                <el-form-item label="活动时间" prop="time">
                    <el-date-picker v-model="formFormatData.formData.time" :disabled="$hasFormEdit" style="width:360px;" :default-time="[`${new Date().getHours()}:${(new Date().getMinutes() + 5).toString().padStart(2,'0')}:00`,'23:59:59']" :picker-options="afterOptions" value-format="timestamp" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="活动渠道" prop="channel">
                    <el-checkbox-group v-model="formFormatData.formData.channel">
                      <el-checkbox label="2" v-if="JSON.stringify($store.getters.power).indexOf('wxapp')>-1">微信小程序</el-checkbox>
                  <el-checkbox label="3" v-if="JSON.stringify($store.getters.power).indexOf('H5')>-1">H5</el-checkbox>
                  <el-checkbox label="4" v-if="JSON.stringify($store.getters.power).indexOf('wechat')>-1">微信公众号</el-checkbox>
                  <el-checkbox label="7" v-if="JSON.stringify($store.getters.power).indexOf('aliapp')>-1">支付宝小程序</el-checkbox>
                  <el-checkbox label="9" v-if="JSON.stringify($store.getters.power).indexOf('toutiaoapp')>-1">抖音-头条</el-checkbox>
                        <!-- <el-checkbox label="2" v-if="$store.getters.power.includes('wxapp')">微信小程序</el-checkbox>
                        <el-checkbox label="3" v-if="$store.getters.power.includes('H5')">H5</el-checkbox>
                        <el-checkbox label="4" v-if="$store.getters.power.includes('wechat')">微信公众号</el-checkbox>
                        <el-checkbox label="7" v-if="$store.getters.power.includes('aliapp')">支付宝小程序</el-checkbox> <el-checkbox label="9" v-if="$store.getters.power.includes('toutiaoapp')">抖音-头条</el-checkbox> -->
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="自定义分享图片">
                    <el-radio-group v-model="formFormatData.formData.activity_share">
                        <el-radio :label="10">默认分享卡</el-radio>
                        <el-radio :label="20">自定义分享卡</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="分享图片" ref="businessbackgroundmap" v-if="formFormatData.formData.activity_share==20">
                    <choose-files ref="chooseFiles" :config="chooseBgConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <div class="form-help">推荐尺寸：750X750，尺寸不匹配时，图片将选取部分展示</div>
                </el-form-item>
                <el-form-item label="">
                    <div class="flex-col">
                        <el-checkbox :true-label="20" :false-label="10" v-model="formFormatData.formData.is_custom">自定义分享文案</el-checkbox>
                        <el-input v-if="formFormatData.formData.is_custom==20" placeholder="输入4-20个字的分享文案" v-model="formFormatData.formData.custom_share_content">
                        </el-input>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div class="wlm-form">
        <div class="wlm-form-header">规则设置</div>
        <div class="wlm-form-content">
            <el-form ref="info" :disabled="$hasFormEnd" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
                <el-form-item label="活动商品" prop="goods_id">
                    <choose-goods ref="chooseGoods" :config="chooseGoodsConfig" :changeEvt="filtersChange"></choose-goods>
                    <el-button v-if="formFormatData.formData.goods_id==''" :disabled="$hasFormEdit" type="primary" @click="goodsToogle">添加商品</el-button>
                    <div class="form-help">砍价活动不与任何平台活动共享</div>
                    <el-table v-if="formFormatData.formData.goods_id!=''" :data="coupon_goods" style="width: 50%">
                        <el-table-column prop="date" label="商品">
                            <template slot-scope="scope">
                                <div class="flex-row">
                                    <img class="logo" v-if="formFormatData.formData.goods.image" :src="formFormatData.formData.goods.image[0]['file_path']">
                                    <div class="inner-text">
                                        <p>{{formFormatData.formData.goods.goods_name}}</p>
                                        <!-- <span>￥:{{scope.row.goods.goods_price}}</span> -->
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <div class="operation-group">
                                    <el-button :disabled="$hasFormEdit" class="wlm-text" type="text" @click="deleteTable(scope)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="砍价商品库存" prop="stock">
                    <el-input placeholder="需小于商品库存" @input.native="clearNativeReg(formFormatData.formData,'stock')" size="small" v-model="formFormatData.formData.stock"></el-input>
                </el-form-item>
                <el-form-item label="是否分销">
                    <el-radio-group v-model="formFormatData.formData.is_dealer">
                        <el-radio :label="1">分销</el-radio>
                        <el-radio :label="2">不分销</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="分销模式">
                    <el-radio-group  v-model="formFormatData.formData.dealer_mode">
                        <el-radio :label="1">分销默认设置</el-radio>
                        <el-radio :label="2">商品单独设置</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="砍价底价" prop="low_price">
                    <el-input :disabled="$hasFormEdit" @blur="notZero(formFormatData.formData,'low_price', {zero: 0})" @input.native="clearNativeReg(formFormatData.formData,'low_price',0,-1,0.01,{zero: ''})" v-model="formFormatData.formData.low_price">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="砍价有效期" prop="effective_time">
                    <div class="input-slot flex-row flex-align-c flex-justify-s wlm-input-appendbox">
                        <el-input-number :disabled="$hasFormEdit" :controls="false" :min="1" :max="48" v-model="formFormatData.formData.effective_time"></el-input-number>
                        <div class="wlm-input-append append-right">小时</div>
                    </div>
                </el-form-item>
                <el-form-item label="帮砍金额">
                    <el-radio-group :disabled="$hasFormEdit" v-model="formFormatData.formData.bargain_type">
                        <el-radio :label="1">随机金额</el-radio>
                        <el-radio :label="2">固定金额</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="帮砍人数" prop="bargain_num">
                    <el-input :disabled="$hasFormEdit" placeholder="2-100" @input.native="clearNativeReg(formFormatData.formData,'bargain_num',2,100,1,{zero: ''})" v-model="formFormatData.formData.bargain_num">
                        <template slot="append">人</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="虚拟成功人数">
                    <el-input @blur="notZero(formFormatData.formData,'virtual_sales', {zero: ''})" @input.native="clearNativeReg(formFormatData.formData,'virtual_sales',1,-1,1,{zero: ''})" v-model="formFormatData.formData.virtual_sales">
                        <template slot="append">人</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="好友砍价获券">
                    <el-button type="primary" @click="couponToogle" style="display: block;margin: 12px 0;">添加优惠券</el-button>
                    <p class="form-help">向砍价好友赠送优惠券，利于砍价好友在平台下单，提高交易量，建议合理添加。</p>
                    <choose-coupon ref="chooseCoupon" :config="chooseCouponConfig" :changeEvt="filtersCouponChange"></choose-coupon>
                    <el-table class="coupon-table" v-if="formFormatData.formData.coupon_id!=''" :data="coupon_name" style="width: 50%;margin-top:20px;">
                        <el-table-column prop="date" label="优惠券名称">
                            <template slot-scope="scope">
                                <p v-if="formFormatData.formData.coupon_name">{{formFormatData.formData.coupon_name}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <div class="operation-group">
                                    <el-button class="wlm-text" type="text" @click="toggleSelection">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div class="wlm-form">
        <div class="wlm-form-header">高级设置</div>
        <div class="wlm-form-content">
            <el-form ref="zko" :disabled="$hasFormEnd" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
                <el-form-item label="购买设置">
                    <el-radio-group :disabled="$hasFormEdit" v-model="formFormatData.formData.buy_setting">
                        <el-radio :label="1">砍到最低价才可购买</el-radio>
                        <el-radio :label="2">最低价前均可购买</el-radio>
                    </el-radio-group>
                    <p class="form-help">允许用户以当前砍到的价格下单购买</p>
                </el-form-item>
                <el-form-item label="发起砍价次数">
                    <el-input :disabled="$hasFormEdit" @input.native="clearNativeReg(formFormatData.formData,'is_buy_num',1,100)" v-model="formFormatData.formData.is_buy_num">
                        <template slot="append">次/人</template>
                    </el-input>
                    <p class="form-help">低于原价时，成功购买该商品计作一次，至多100次</p>
                </el-form-item>
                <el-form-item label="帮砍次数">
                    <el-input :disabled="$hasFormEdit" @input.native="clearNativeReg(formFormatData.formData,'help_num',1,100)" v-model="formFormatData.formData.help_num">
                        <template slot="append">次/人</template>
                    </el-input>
                    <p class="form-help">每个用户可帮好友砍价的次数，单个活动限帮砍次数，至多100次</p>
                </el-form-item>
                <el-form-item label="推荐商品">
                    <el-radio-group v-model="formFormatData.formData.is_recommend">
                        <el-radio :label="1">个性化推荐</el-radio>
                        <el-radio :label="2">手动选择</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="选择商品" v-if="formFormatData.formData.is_recommend=='2'">
                    <choose-goods ref="recomChooseGoods" :config="recomChooseGoodsConfig" :changeEvt="recomFiltersChange"></choose-goods>
                    <el-button type="primary" @click="recomGoodsToogle" style="margin-bottom:14px;">添加商品</el-button>
                    <el-table v-if="formFormatData.formData.recommend_goods!=''" :data="formFormatData.formData.recommend_goods" style="width: 50%">
                        <el-table-column prop="date" label="商品">
                            <template slot-scope="scope">
                                <div class="flex-row">
                                    <img class="logo" v-if="scope.row.image && scope.row.image" :src="scope.row.image[0]['file_path']">
                                    <div class="inner-text">
                                        <p>{{scope.row.goods_name}}</p>
                                        <span>￥:{{scope.row.goods_price}}</span>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <div class="operation-group">
                                    <el-button class="wlm-text" type="text" @click="recomDeleteTable(scope)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <!-- <el-form-item label="社群服务">
                  <el-select v-model="formFormatData.formData.community_type" placeholder="请选择客服类型" class="poster" @change="communitybtn">
                      <el-option :label="'社群'" :value="1">
                      </el-option>
                      <el-option :label="'客服'" :value="2">
                      </el-option>
                      <el-option :label="'公众号'" :value="3">
                      </el-option>
                      <el-option :label="'电话'" :value="4">
                      </el-option>
                  </el-select>
                   <el-select v-model="formFormatData.formData.community_id" placeholder="请选择" style="width:200px;"  v-if="!!formFormatData.formData.community_type">
                    <el-option v-for="(item,index) in selectValue" :key="index" :label="item.title" :value="item.id" ></el-option>
                  </el-select>
              </el-form-item> -->
              <el-form-item label="砍价说明">
                    <ueditor
                                v-if="isFirst"
                                :ueditorChange="shopInfoChange"
                                :ueditorList="ueditorList"
                                :bindIndex="1"
                                :defaultMsg='defaultMsg1'
                                :config='{initialFrameWidth: null,initialFrameHeight: 350}'
                                ref="by_know"></ueditor>
              </el-form-item>

            </el-form>
        </div>
    </div>
    <div v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
        <el-button size="small" @click="saveForm" type="primary" :loading="loading">保存</el-button>
        <router-link tag="span" to="/application/bargain">
            <el-button size="small">返回</el-button>
        </router-link>
    </div>
</div>
</template>

<script>
import ChooseGoods from '@/components/ChooseGoods/index'
import ChooseCoupon from '@/components/ChooseCoupon/index'
import ChooseFiles from '@/components/ChooseFiles/index'
  import ueditor from '@/components/Ueditor/index'
import {
  setBargainData,
  getBargainData
} from '@/api/application'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Form')],
  name: 'BargainAdd',
  components: {
    ChooseGoods,
    ChooseFiles,
    ChooseCoupon,
    ueditor
  },
  created() {
     this.$nextTick(() => {
        if(this.$route.query.id){
                  this.getBargainData()
              }
    })
  },
  computed: {
    getPath() {
      return function(path) {
        return (path.includes('https://') || path.includes('http://')) ? `${path}` : require(`@/assets/custorm_style/${path}`)
      }
    },
    // 进行中不能改
    $hasFormEdit() {
      return this.isFormEdit && this.formFormatData.formData.status !== 1
    },
    // 结束了才不能改
    $hasFormEnd() {
      return this.isFormEdit && this.formFormatData.formData.status === 4
    }
  },
  data() {
    var checkTime = (rule, value, callback) => {
      const { message } = rule
      const time = this.formFormatData.formData.time
      if ((Array.isArray(time) && time.length === 0) || !Array.isArray(time)) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }

    return {
      isFirst:false,
      ueditorList: [],
       defaultMsg1: '',
      selectValue:[],
      loading: false,
      coupon_name: [{}],
      coupon_goods: [{}],
      currentRow: [],
      chooseCouponConfig: {
        type: ['chooseCoupon'],
        model: 'display',
        get_limit_type: 0,
        disabled: [
          {
            label: 'get_limit_type',
            value: 1
          }],
        initList: []
      },
      recomChooseGoodsConfig: {
        type: ['chooseGoods'],
        model: 'normal',
        initList: []
      },
      chooseBgConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          isMore: true,
          model: 'display'
        },
        isUnique: true,
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'share_image_id',
          model: 'img'
        }
      },
      chooseGoodsConfig: {
        type: ['chooseGoods'],
        model: 'normal',
        unique: true,
        bargain: 'bargain',
        disabled: [{
          label: 'sale_type',
          value: 0,
          reverse: true
        }, {
          label: 'member_exclusive',
          value: 1
        }, {
          label: 'transport_type',
          value: 30
        }],
        initList: []
      },
      chooseData: [],
      formFormatData: {
        key: ['active', 'info', 'zko'],
        api: {
          editForm: {
            // api: getBargainData,
            params: {
              id: ''
            },
            filters: {
              choose: {
                bindInit: ['chooseGoodsConfig', 'recomChooseGoodsConfig']
              },
              img: {
                bindInit: ['chooseBgConfig']
              }
            }
          },
          submitForm: setBargainData
        },
        formData: {
          explain:'',
          community_type:'',
          community_id:'',
          low_price: '',
          is_dealer: 2,
          dealer_mode: 1,
          bargain_num: '',
          virtual_sales: '',
          name: '',
          effective_time: '4',
          status: '',
          time: [],
          channel: [],
          stock: '',
          bargain_type: 1,
          goods_id: '',
          goods: {},
          id: '',
          recommend_goods: [],
          help_num: '1',
          is_buy_num: '1',
          buy_setting: 1,
          is_recommend: 1,
          coupon_id: '',
          activity_share: 10,
          share_image_id: [],
          is_custom: 10,
          custom_share_content: '',
          coupon_name: ''
        },
        rules: {
          name: [{
            message: '请填写活动名称',
            required: true,
            trigger: 'change'
          }],
          stock: [{
            message: '请填写砍价商品库存',
            required: true,
            trigger: 'change'
          }],
          goods_id: [{
            message: '请添加活动商品',
            required: true,
            trigger: 'change'
          }],
          bargain_num: [{
            message: '请填写帮砍人数',
            required: true,
            trigger: 'change'
          }],
          effective_time: [{
            message: '请填写砍价有效期',
            required: true,
            trigger: 'change'
          }],
          low_price: [{
            message: '请填写砍价底价',
            required: true,
            trigger: 'change'
          }],
          channel: [{
            message: '请填写活动渠道',
            required: true,
            trigger: 'change'
          }],
          time: [{
            message: '请选择活动时间',
            required: true,
            validator: checkTime,
            trigger: 'change'
          }]
        }
      }
    }
  },
   mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.isFirst = true
      }, 500)
 
    })
  },
  methods: {
    // communitybtn(val){
    //   servicesList({list_rows: 'all' }).then(res=>{
    //     this.selectValue = res.data.data
    //   })
    // },
    getBargainData(){
        this.loading = true

      getBargainData({id:this.$route.query.id}).then(res=>{
        if(res.data.code==1){
          this.loading = false
           this.formFormatData.formData = res.data.data
           this.defaultMsg1=res.data.data.explain
        }
      })
    },
    recomFiltersChange(val) {
      const { displayData } = val
      console.log(val)
      displayData.map(item => {
        var hasIndex = this.formFormatData.formData.recommend_goods.findIndex(tableitem => { return `${tableitem.goods_id}` === `${item.goods_id}` })
        if (hasIndex === -1 && this.formFormatData.formData.recommend_goods.length < 8) {
          this.formFormatData.formData.recommend_goods.push({ image: [{ file_path: item.image[0]['file_path'] }], goods_name: item.goods_name, goods_id: item.goods_id, goods_price: item.goods_min_price })
        }
      })
    },
    recomGoodsToogle() {
      const result = []
      this.formFormatData.formData.recommend_goods.map(item => {
        result.push(item.goods_id)
      })
      this.$refs.recomChooseGoods.currentRow = result
      this.$refs.recomChooseGoods.toggle()
    },
    recomDeleteTable(scope) {
      this.formFormatData.formData.recommend_goods.splice(scope.$index, 1)
      this.currentRow.splice(scope.$index, 1)
    },
     shopInfoChange(msg) {
            this.defaultMsg1 = msg
            },
    formFormatCallBack(data, type, response) {
      console.log("2222222llllllllllllllldddddd",data,type,response)
      if (type === 'editForm') {
        // if (this.isFormEdit && this.formFormatData.formData.status !== 3) {
        //   this.$refs.by_know.setDisabled()
        // }
          const { explain } = data
                    this.defaultMsg1 = explain
        
      }
    },
    saveForm() {
       this.formFormatData.formData.explain = this.defaultMsg1
      this.formFormatSubmit({ router: { type: 'replace', path: '/application/bargain', code: 1 } })
    },
    filtersChange(val) {
      // this.currentRow = val.currentRow
      const displayData = val.displayData
      const disLast = displayData.pop()
      this.formFormatData.formData.goods_id = disLast['goods_id']
      this.formFormatData.formData.goods.goods_name = disLast['goods_name']
      this.formFormatData.formData.goods.image = [disLast['image'][0]]
      this.coupon_goods = [{}]
    },
    goodsToogle() {
      this.$refs.chooseGoods.toggle()
    },
    deleteTable(scope) {
      this.formFormatData.formData.goods_id = ''
    },
    filtersCouponChange(arg) {
      const { displayData } = arg
      const dislength = displayData.length - 1
      console.log(displayData, 'xx')
      displayData.map(item => {
        this.formFormatData.formData.coupon_id = displayData[dislength]['coupon_id']
        this.formFormatData.formData.coupon_name = displayData[dislength]['name']
      })
      // this.coupon_name = [{}]
    },
    couponToogle() {
      this.$refs.chooseCoupon.toggle()
    },
    toggleSelection() {
      this.formFormatData.formData.coupon_id = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.bargain-add {
    .logo {
        height: 40px;
        width: 40px;
        border-radius: 50%;
        vertical-align: middle;
        margin-right: 6px;
    }
}
</style>
